package io.gitee.wl4837.alatool.core.lang;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author wangliang
 */
public class Url {

    private String url;

    public Url(String url) {
        this.url = url;
    }

    public String getHost() {
        return "";
    }

    public String setHost() {
        return "";
    }

    public String getUserInfo() {
        return "";
    }

    public String setUserInfo() {
        return "";
    }

    public String getHeader() {
        return "";
    }

    public String setHeader() {
        return "";
    }

    public String getBody() {
        return "";
    }

    public String setBody() {
        return "";
    }

    public String getUrl() {
        return "";
    }

    public String setUrl() {
        return "";
    }

    public String getPath() {
        return "";
    }

    public String setPath() {
        return "";
    }

    public String getRef() {
        return "";
    }

    public String setRef() {
        return "";
    }

    public String getAuthority() {
        return "";
    }

    public String setAuthority() {
        return "";
    }

    public String getQuery() {
        return "";
    }

    public String setQuery() {
        return "";
    }

    public Integer getPort() {
        Pattern pattern = Pattern.compile(":(\\d+)");
        Matcher matcher = pattern.matcher(url);
        if (matcher.find()) {
            return Integer.parseInt(matcher.group(1));
        } else {
            return null;
        }
    }

    public void setPort(Integer port) {
        Pattern pattern = Pattern.compile(":(\\d+)");
        Matcher matcher = pattern.matcher(this.url);
        if (matcher.find()) {
            if (port == null) {
                this.url = this.url.replaceFirst(":(\\d+)", "");
            } else {
                this.url = this.url.replaceFirst(":(\\d+)", ":" + port);
            }
        } else {
            throw new RuntimeException("The port section was not found");
        }
    }

    public String getProtocol() {
        Pattern pattern = Pattern.compile("^([a-zA-Z0-9\\-+.]+)://");
        Matcher matcher = pattern.matcher(this.url);
        if (matcher.find()) {
            return matcher.group(1);
        } else {
            throw new RuntimeException("The protocol section was not found");
        }
    }

    public void setProtocol(String protocol) {
        Pattern pattern = Pattern.compile("^([a-zA-Z0-9\\-+.]+)://");
        Matcher matcher = pattern.matcher(this.url);
        if (matcher.find()) {
            this.url = this.url.replaceFirst("^([a-zA-Z0-9\\-+.]+)://", protocol + "://");
        } else {
            throw new RuntimeException("The protocol section was not found");
        }
    }

}
